package com.zzy.chattoai.service;

import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.request.ResponseFormat;
import dev.langchain4j.model.chat.request.ResponseFormatType;
import dev.langchain4j.model.chat.request.json.JsonObjectSchema;
import dev.langchain4j.model.chat.request.json.JsonSchema;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;

@Service
@Slf4j
public class ChatService {


    @Resource
    private Assistant assistant;

    @Resource
    private AssistantStream assistantStream;


    public Flux<ServerSentEvent<String>> chatStream(String memoryId, String message) {

        log.info("接收到问题{}", message);
        Flux<String> flux = assistantStream.chatStream(memoryId, message);
        Flux<ServerSentEvent<String>> map = flux.map(chunk -> ServerSentEvent.<String>builder()
                .data(chunk)
                .build());

        return map;
    }


    public String chatWithMessage(UserMessage userMessage) {
        String chatResponse = assistant.chat(userMessage);
        log.info("响应内容{}", chatResponse);

        return chatResponse;
    }


    public String chatSystemPro(String message) {

        String chat = assistant.chatPro(message);
        log.info("AI响应内容{}", chat);

        return chat;


    }

    public String chat(String message) {
        String chat = assistant.chat(message);
        return chat;
    }


    public String chatJson(String message) {

        UserMessage userMessage = UserMessage.from(message);
        ResponseFormat responseFormat = ResponseFormat.builder()
                .type(ResponseFormatType.JSON)
                .jsonSchema(JsonSchema.builder()
                        .name("Person")
                        .rootElement(JsonObjectSchema.builder()
                                .addStringProperty("name")
                                .addIntegerProperty("age")
                                .addNumberProperty("height")
                                .addBooleanProperty("married")
                                .required("name", "age", "height", "married")
                                .build())
                        .build())
                .build();
        ChatRequest chatRequest = ChatRequest.builder()
                .responseFormat(responseFormat)
                .messages(userMessage)
                .build();

        String chat = assistant.chat(chatRequest);
        return chat;


    }
}
